import { Route } from "vitepress";
import * as path from "path";
import * as fs from "fs";
import { rewritesRouter } from "../setup/constant";

export function findSourceDir(baseUrl) {
  const files = import.meta.globEager("@/**/*.md");

  let routers: Route[] = [];

  for (const f in files) {
    const o = files[f].default;
    if (rewritesRouter.hasOwnProperty(f.substring(1))) {
      const path = rewritesRouter[f.substring(1)];
      o.path = path.substring(0, path.length - 3);
    } else {
      o.path = o.path || f.substring(0, f.length - 3);
    }
    o.path = baseUrl
      ? baseUrl.substring(0, baseUrl.length - 1) + o.path
      : o.path;
    o.pageData = files[f]["__pageData"];
    if (o.pageData.frontmatter.layout !== "home") {
      routers.push(o);
    }
  }
  return routers;
}

export function findAllFiles(url) {
  return new Promise((resolve, reject) => {
    // 收集所有的文件路径
    const arr = [];
    let timer = null;
    const fileDisplay = (url, cb) => {
      const filePath = path.resolve(url);
      //根据文件路径读取文件，返回文件列表
      fs.readdir(filePath, (err, files) => {
        if (err) return console.error("Error:(spec)", err);
        files.forEach((filename) => {
          //获取当前文件的绝对路径
          const filedir = path.join(filePath, filename);
          // fs.stat(path)执行后，会将stats类的实例返回给其回调函数。
          fs.stat(filedir, (eror, stats) => {
            if (eror) return console.error("Error:(spec)", err);
            // 是否是文件
            const isFile = stats.isFile();
            // 是否是文件夹
            const isDir = stats.isDirectory();
            if (isFile) {
              // 这块我自己处理了多余的绝对路径，第一个 replace 是替换掉那个路径，第二个是所有满足\\的直接替换掉
              arr.push(filedir.replace(__dirname, "").replace(/\\/gim, "/"));
              // 最后打印的就是完整的文件路径了
              if (timer) clearTimeout(timer);
              timer = setTimeout(() => cb && cb(arr), 200);
            }
            // 如果是文件夹
            if (isDir) fileDisplay(filedir, cb);
          });
        });
      });
    };
    fileDisplay(url, (arr) => {
      resolve(arr);
    });
  });
}

export function fileWatch(url) {
  const watcher = fs.watch(url, (eventType, filename) => {
    if (eventType === "rename") {
      // 如果文件名改变
      console.log(`文件 ${filename} 文件名改变`);
    } else if (eventType === "change") {
      console.log(`文件 ${filename} 文件内容改变`);
    } else if (eventType === "error") {
      // 如果发生错误
      // console.log(`Error occurred while watching ${filename}`);
    }
  });
  return watcher;
}
